"""
该模块包含系统中的其他辅助视图函数，如首页、登录、角色切换等功能。
"""

# 导入 Django 核心模块
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseForbidden
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.conf import settings

# 导入项目模型
from ..models import UserRoleAssignment, Grade


# 首页视图函数
def index(request):
    """
    渲染系统首页模板。

    根据用户登录状态，向模板传递不同的上下文信息。

    :param request: Django请求对象
    :type request: django.http.HttpRequest
    :return: 渲染后的首页页面
    :rtype: django.http.HttpResponse
    """
    context = {
        "is_authenticated": request.user.is_authenticated,
        "username": request.user.username if request.user.is_authenticated else "",
    }
    return render(request, "index.html", context)


def switch_role(request):
    """
    展示用户可切换的角色列表视图。

    获取当前登录用户的所有活跃角色，并渲染角色切换页面。

    :param request: Django请求对象
    :type request: django.http.HttpRequest
    :return: 渲染后的角色切换页面
    :rtype: django.http.HttpResponse
    """
    # 获取用户的所有活跃角色
    role_assignments = UserRoleAssignment.objects.filter(
        user=request.user, is_active=True
    ).select_related("role")
    roles = [assignment.role for assignment in role_assignments]
    return render(request, "switch_role.html", {"roles": roles})


def switch_role_submit(request, rolename):
    """
    处理用户角色切换请求。

    验证请求方法，设置用户当前角色到session，并 redirect到首页。
    对于年级组长角色，同时设置GRADE_ID到session中。

    :param request: Django请求对象
    :type request: django.http.HttpRequest
    :param rolename: 要切换的角色名称
    :type rolename: str
    :return: 重定向响应或403禁止访问响应
    :rtype: django.http.HttpResponseRedirect or django.http.HttpResponseForbidden
    """
    # 导入Grade模型
    from core.models import Grade

    # 验证请求方法
    if request.method == "POST":
        # 验证角色是否有效（用户是否拥有该角色）
        has_role = UserRoleAssignment.objects.filter(
            user=request.user, role__name=rolename, is_active=True
        ).exists()

        if has_role:
            request.session["CURRENT_ROLE"] = rolename

            # 如果是年级组长角色，设置GRADE_ID
            if rolename == "principal":
                return redirect("core:principal_dashboard")
            elif rolename == "grade_leader":
                grade_id = Grade.objects.filter(grade_leader=request.user).first().id
                request.session["GRADE_ID"] = grade_id
                return redirect("core:grade_leader_dashboard", grade_id)
                
            elif rolename == "homeroom_teacher":
                from core.models import ClassInfo
                class_id = ClassInfo.objects.filter(homeroom_teacher=request.user).first().id
                request.session["CLASS_ID"] = class_id
                return redirect("core:home_teacher_dashboard", class_id)
            elif rolename == "teacher":
                return redirect("core:teacher_dashboard")
            elif rolename == "ASSISTANT":
                return redirect("core:index")
            else:
                # 默认重定向到首页，确保所有路径都有返回值
                return redirect("core:index")
        else:
            return HttpResponseForbidden("您没有权限切换到该角色")
    else:
        return HttpResponseForbidden("仅允许POST请求")


# 登录视图函数
def login(request):
    """
    处理用户登录请求。

    支持用户登录认证和密码找回功能。认证成功后根据用户角色数量决定是否重定向到角色切换页面。
    登录失败时显示错误信息。

    :param request: Django请求对象
    :type request: django.http.HttpRequest
    :return: 重定向响应或登录页面
    :rtype: django.http.HttpResponseRedirect or django.http.HttpResponse
    """
    error_message = ""

    if request.method == "POST":
        # 处理登录提交
        if "login_submit" in request.POST:
            username = request.POST.get("username")
            password = request.POST.get("password")
            # 认证用户
            user = authenticate(request, username=username, password=password)
            # 查询用户是否已经分配了权限，当前学期是否分配了学科，是否分配了年级和班级，如果有个没有分配则给出提示
            from core.models import (
                UserRoleAssignment,
                Semester,
                TeacherSubjectAssignment,
                Grade,
                ClassInfo,
            )

            current_semester = Semester.objects.filter(is_current=True).first()
            role_assignments = UserRoleAssignment.objects.filter(
                user=user, semester=current_semester, is_active=True
            )
            subject_assignment = TeacherSubjectAssignment.objects.filter(
                teacher=user, semester=current_semester
            ).first()
            grade = Grade.objects.filter(grade_leader=user).first()
            class_info = ClassInfo.objects.filter(
                homeroom_teacher=user, semester=current_semester
            ).first()

            if not role_assignments.exists():
                error_message = "您没有分配权限，请联系管理员。"
            elif not subject_assignment:
                error_message = "您当前学期没有分配学科，请联系管理员。"
            elif not grade:
                error_message = "您当前学期没有分配年级，请联系管理员。"
            elif not class_info:
                error_message = "您当前学期没有分配班级，请联系管理员。"

            if user is not None:
                auth_login(request, user)

                # 获取用户的所有活跃角色
                role_assignments = UserRoleAssignment.objects.filter(
                    user=request.user, is_active=True
                ).select_related("role")
                roles = [assignment.role for assignment in role_assignments]

                # 根据角色数量决定跳转
                if len(roles) > 1:
                    request.session["CURRENT_ROLE"] = roles[0].name
                    return redirect("core:switch_role")  # 多角色，重定向到角色切换页面
                elif len(roles) == 1:
                    request.session["CURRENT_ROLE"] = roles[0].name
                    return redirect("index")  # 单角色，直接跳转首页
                else:
                    error_message = "您没有可用的角色，请联系管理员。"
            else:
                error_message = "用户名或密码错误"

        # 处理找回密码提交
        elif "forgot_password_submit" in request.POST:
            email = request.POST.get("email")

            try:
                user = User.objects.get(email=email)
                subject = "找回密码"
                message = f"请点击以下链接重置密码：{settings.BASE_URL}/reset-password/{user.id}/"
                send_mail(subject, message, settings.EMAIL_HOST_USER, [email])
                error_message = "重置密码邮件已发送，请检查您的邮箱。"
            except User.DoesNotExist:
                error_message = "该邮箱未注册，请检查后重试。"

    # 处理GET请求或登录失败，返回登录表单
    return render(request, "login.html", {"error_message": error_message})


def custom_403(request, exception):
    """自定义403无权限页面"""
    return render(request, "403.html", status=403)
